package ru.maksb.exchange.service;

import static java.lang.String.format;

import java.io.ObjectInputStream.GetField;
import java.util.concurrent.atomic.AtomicInteger;

import ru.maksb.exchange.domain.request.NewOrderRequest;
import ru.maksb.exchange.domain.request.Request;
import ru.maksb.exchange.domain.response.Response;

public class ResponseFactory {
    private static AtomicInteger sequenceId = new AtomicInteger();
    public final static String HEARTBEAT_TAMPLATE = "sequenceId=%s;a";
    public final static String LOGIN_TEMPLATE = "sequenceId=%s;login=%s"; 
    public final static String LOGIN_RESULT_OK_TEMPLATE = "sequenceId=%s;msgType=loginClientOk";
    public final static String LOGIN_RESULT_INVALID_NAME = "sequenceId=%s;msgType=loginErrorInvalidName";
    public final static String LOGIN_RESULT_DUPLICATE_NAME = "sequenceId=%s;msgType=loginErrorDuplicateName";
    
    public final static String INVALID_MSG = "sequenceId=%s;clientSequenceId=%s;msgType=invalidMsg";
    
    public final static String NEW_ORDER_RESULT_OK = "sequenceId=%s;referenceId=%s;msgType=newOrderOk;ticket=%s;type=%s;side=%s;amount=%s;price=%s";
    
    private final static String CANCEL_ORDER_OK = "sequenceId=%s;referenceId=%s;msgType=cancelOrderDone";
    private final static String CANCEL_ORDER_ERROR = "sequenceId=%s;referenceId=%s;msgType=cancelOrderError";
    
    
    public static String loginResultOk() {
        return format(LOGIN_RESULT_OK_TEMPLATE, sequenceId.getAndIncrement());
    }
    
    public static String invalidMessage(String clientSequence) {
        return format(INVALID_MSG, sequenceId.getAndIncrement(), clientSequence);
    }

    public static String newOrderResultOk(NewOrderRequest request) {
        return format(NEW_ORDER_RESULT_OK, sequenceId.getAndIncrement(),
                                           request.getReferenceId(),
                                           request.getTicket(),
                                           request.getType().getCode(),
                                           request.getSide().getCode(),
                                           request.getAmount(),
                                           request.getPrice());
    }

    public static String cancelOrderOk(Response response) {
        return format(CANCEL_ORDER_OK, sequenceId.getAndIncrement(),
                                       response.getReferenceId());
    }

     static String cancelOrderError(Response response) {
         return format(CANCEL_ORDER_ERROR, sequenceId.getAndIncrement(),
                 response.getReferenceId());
    }

    public static String heartbeat() {
        return format(HEARTBEAT_TAMPLATE, sequenceId.getAndIncrement());
    }
}
